package cn.jinjimi.domain.data;

import cn.jinjimi.app.controller.event.DataEvent;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by zhenhua on 16/7/20.
 */
public class EventFactory {

    public static <T extends DataEvent> T create(Class<T> tClass, Object... params) {

        T event = null;

        try {

            Constructor<T> constructor = tClass.getConstructor();
            event = constructor.newInstance();

            if (params != null) {

                if (params.length > 2) {
                    Field state = tClass.getField("state");
                    Field error = tClass.getField("error");
                    Field msg = tClass.getField("msg");

                    state.set(event, params[0]);
                    error.set(event, params[1]);
                    msg.set(event, params[2]);
                }

                if (params.length > 3) {
                    Field data = tClass.getDeclaredField("data");
                    data.set(event, params[3]);
                }
            }

        } catch (NoSuchMethodException e) {
            //e.printStackTrace();
        } catch (IllegalAccessException e) {
            //e.printStackTrace();
        } catch (InstantiationException e) {
            //e.printStackTrace();
        } catch (InvocationTargetException e) {
            //e.printStackTrace();
        } catch (NoSuchFieldException e) {
            //e.printStackTrace();
        }

        return event;
    }

    public static <E extends DataEvent> E create(E event, Object... params){

        if(event!=null) {
            try {

                Class<?> tClass = event.getClass();

                Field state = tClass.getField("state");
                Field data = tClass.getField("data");
                Field error = tClass.getField("error");
                Field msg = tClass.getField("msg");

                if (params != null) {

                    if (params.length > 2) {
                        state.set(event, params[0]);
                        error.set(event, params[1]);
                        msg.set(event, params[2]);
                    }

                    if (params.length > 3) {
                        data.set(event, params[3]);
                    }
                }

            } catch (NoSuchFieldException e) {
                //e.printStackTrace();
            } catch (IllegalAccessException e) {
                //e.printStackTrace();
            } catch (IllegalArgumentException e) {
                //e.printStackTrace();
            }
        }

        return event;
    }
}
